import { requestPermissionListData, requestUserList } from "../../../services/permission_services";
import { SET_PERMISSION_LIST, SET_USER_LIST_DATA, SET_TARGET_KEYS } from "./action_types";

const setPermissionListData = data => ({
  type: SET_PERMISSION_LIST,
  list: data
});

const setUserListData = (list, mockData, targetKeys) => ({
  type: SET_USER_LIST_DATA,
  list,
  mockData,
  targetKeys
});

export const getPermissionListData = () => {
  return async dispatch => {
    let data = await requestPermissionListData();
    data['item_list'].forEach(item => {
      item.key = item.id;
    });
    dispatch(setPermissionListData(data['item_list']))
  }
};

export const getUserListData = () => {
  return async dispatch => {
    const mockData = [];
    const targetKeys = [];
    const data = await requestUserList();
    const result = data.result;
    if (result && result.length > 0) {
      result.forEach(item => {
        const data = {
          key: item['user_id'],
          title: item['user_name'],
          status: item.status
        };
        if (data.status === 1) {
          targetKeys.push(data.key);
        }
        mockData.push(data);
      });
    }
    dispatch(setUserListData(data.result, mockData, targetKeys));
  }
};

export const setTargetKeys = targetKeys =>({
  type: SET_TARGET_KEYS,
  targetKeys
});
